/*
* @Author: An
* @Date:   2017-07-08 15:27:14
* @Last Modified by:   An
* @Last Modified time: 2017-07-09 16:45:22
*/

'use strict';

require('page/common/header/index.js');
require('page/common/nav/index.js');
require('./index.css');
var _xj 			= require('util/xj.js');
var _user 			= require('service/user-service.js');
var templateIndex 	= require('./index.string');
var navSide 		= require('page/common/nav-side/index.js');

// page逻辑
var page = {
	init : function() {
		this.onLoad();
		this.bindEvent();
	},
	onLoad : function() {
		// 初始化左侧菜单
		navSide.init({
			name : 'user-center'
		});
		this.loadUserInfo();
	},
	bindEvent : function() {
		var _this = this;
		// 点击提交按钮后的动作
		$(document).on('click', '.btn-submit', function() {
			var userInfo = {
				phone 		: $.trim($('#phone').val()),
				email 		: $.trim($('#email').val()),
				question 	: $.trim($('#question').val()),
				answer 		: $.trim($('#answer').val())
			},
			validateResult = _this.validateForm(userInfo);
			if (validateResult.status) {
				_user.updateUserInfo(userInfo, function(res) {
					_xj.successTips(msg);
					window.location.href = './user-center.html';
				}, function(errMsg) {
					_xj.errorTips(errMsg);	
				});
			} else {
				_xj.errorTips(validateResult.msg);
			}
		});
	},
	loadUserInfo : function() {
		var userHtml = '';
		_user.getUserInfo(function(res) {
			userHtml = _xj.renderHtml(templateIndex, res);
			$('.panel-body').html(userHtml);
		}, function(errMsg) {
			_xj.errorTips(errMsg);
		});
	},
	validateForm : function(formData) {
		var result = {
			status 	: false,
			msg 	: ''
		};
		if (!_xj.validate(formData.phone, 'phone')) {
			result.msg = '手机号格式不正确';
			return result;
		}
		if (!_xj.validate(formData.email, 'email')) {
			result.msg = '邮箱格式不正确';
			return result;
		}
		if (!_xj.validate(formData.question, 'require')) {
			result.msg = '密码提示问题不能为空';
			return result;
		}
		if (!_xj.validate(formData.answer, 'require')) {
			result.msg = '密码提示问题答案不能为空';
			return result;
		}
		// 通过验证，返回正确提示
		result.status 	= true;
		result.msg 		= '登录成功';
		return result;
	}
};

$(function() {
	page.init();
});